package com.sservice.base.utils.image;


import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;

/**
 * <p>Title: PictureMerge</p>
 * <p>Description: 图片合并</p>
 * <p>Company: DINGGE</p>
 * Created by suweiming on 2018/11/1.
 */
public class PictureMerge {
    /**
     * @param fileUrl 文件绝对路径或相对路径
     * @return 读取到的缓存图像
     * @throws IOException 路径错误或者不存在该文件时抛出IO异常
     */
    public static BufferedImage getBufferedImage(String fileUrl) throws IOException {
        File f = new File(fileUrl);
        return ImageIO.read(f);
    }

    /**
     * @param savedImg 待保存的图像
     * @param saveDir  保存的目录
     * @param fileName 保存的文件名，必须带后缀，比如 "beauty.jpg"
     * @param format   文件格式：jpg、png或者bmp
     * @return
     */
    public static boolean saveImage(BufferedImage savedImg, String saveDir, String fileName, String format) {
        boolean flag = false;
        // 先检查保存的图片格式是否正确
        String[] legalFormats = {"jpg", "JPG", "png", "PNG", "bmp", "BMP"};
        int i = 0;
        for (i = 0; i < legalFormats.length; i++) {
            if (format.equals(legalFormats[i])) {
                break;
            }
        }
        if (i == legalFormats.length) { // 图片格式不支持
            System.out.println("不是保存所支持的图片格式!");
            return false;
        }

        // 再检查文件后缀和保存的格式是否一致
        String postfix = fileName.substring(fileName.lastIndexOf('.') + 1);
        if (!postfix.equalsIgnoreCase(format)) {
            System.out.println("待保存文件后缀和保存的格式不一致!");
            return false;
        }

        String fileUrl = saveDir + fileName;
        File file = new File(fileUrl);
        try {
            flag = ImageIO.write(savedImg, format, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 待合并的两张图必须满足这样的前提，如果水平方向合并，则高度必须相等；如果是垂直方向合并，宽度必须相等。
     * mergeImage方法不做判断，自己判断。
     *
     * @param img1         待合并的第一张图
     * @param img2         带合并的第二张图
     * @param isHorizontal 为true时表示水平方向合并，为false时表示垂直方向合并
     * @return 返回合并后的BufferedImage对象
     * @throws IOException
     */
    public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, boolean isHorizontal, int startX, int startY) throws IOException {
        int w1 = img1.getWidth();
        int h1 = img1.getHeight();
        int w2 = img2.getWidth();
        int h2 = img2.getHeight();

        // 从图片中读取RGB
        int[] ImageArrayOne = new int[w1 * h1];
        ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
        int[] ImageArrayTwo = new int[w2 * h2];
        ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);

        // 生成新图片
        BufferedImage DestImage = null;
        if (isHorizontal) { // 水平方向合并
            DestImage = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(startX, startY, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB
        } else { // 垂直方向合并
            DestImage = new BufferedImage(w1, h1 + h2, BufferedImage.TYPE_INT_RGB);
            DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            DestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB
        }
        return DestImage;
    }

    public static BufferedImage merge2Image(BufferedImage img1, BufferedImage img2, int offsetX, int offsetY) throws IOException {
        int w2 = img2.getWidth();
        int h2 = img2.getHeight();

        // 从图片中读取RGB
        int[] ImageArrayTwo = new int[w2 * h2];
        ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);

        // 生成新图片
        img1.setRGB(offsetX, 0, w2, h2, ImageArrayTwo, 0, w2); // 设置下半部分的RGB
        return img1;
    }

    /**
     * <p>Title: getImageStream</p>
     * <p>Description: 获取图片InputStream</p>
     *
     * @param destImg
     * @return
     */
    public static InputStream getImageStream(BufferedImage destImg) {
        InputStream is = null;

        BufferedImage bi = destImg;

        ByteArrayOutputStream bs = new ByteArrayOutputStream();

        ImageOutputStream imOut;
        try {
            imOut = ImageIO.createImageOutputStream(bs);

            ImageIO.write(bi, "png", imOut);

            is = new ByteArrayInputStream(bs.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    /**
     * <p>Title: drawTextInImg</p>
     * <p>Description: 图片上添加文字业务需求要在图片上添加水</p>
     *
     * @param filePath
     * @param outPath
     * @param text
     */
    public static BufferedImage drawTextInImg(BufferedImage bimage, FontText text, int width, int top) {
        Graphics2D g = bimage.createGraphics();
        g.setColor(getColor(text.getWm_text_color()));
        g.setBackground(Color.white);
        Font font = new Font(text.getWm_text_font(), Font.PLAIN,
                text.getWm_text_size());
        g.setFont(font);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 抗锯齿
        // 计算文字长度，计算居中的x点坐标
        FontMetrics fm = g.getFontMetrics(font);
        int textWidth = fm.stringWidth(text.getText());
        int widthX = (width - textWidth) / 2;
        // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
        g.drawString(text.getText(), widthX, top);
        g.dispose();
        return bimage;
    }

    // color #2395439
    public static Color getColor(String color) {
        if (color.charAt(0) == '#') {
            color = color.substring(1);
        }
        if (color.length() != 6) {
            return null;
        }
        try {
            int r = Integer.parseInt(color.substring(0, 2), 16);
            int g = Integer.parseInt(color.substring(2, 4), 16);
            int b = Integer.parseInt(color.substring(4), 16);
            return new Color(r, g, b);
        } catch (NumberFormatException nfe) {
            return null;
        }
    }
    /**
     * <p>Title: myQr</p>
     * <p>Description: 生成我的二维码</p>
     * @param headurl
     * @param wxqr
     * @return
     */
    /**
     * <p>Title: myQr</p>
     * <p>Description: </p>
     *
     * @param thumbnail 拼团主题Banner图
     * @return
     */
    public static BufferedImage myQrCard(String title, String banner, String qrUrl) {
        // 读取待合并的文件
        BufferedImage bi2 = null;
        BufferedImage bi3 = null;
        // 调用mergeImage方法获得合并后的图像
        BufferedImage destImg = null;
        try {
            // 团购缩略图
            if (banner == null) {
                banner = "/Users/suweiming/projects/wb/xcx-service/sservice-base/src/main/java/qrimg/banner.jpg";
                bi2 = ImageIO.read(new File(banner));
            } else {
                bi2 = ImageIO.read(new URL(banner));
            }
            bi2 = ImageUtil.zoomInImage(bi2, 500);

            // 小程序二维码
            String headurl = qrUrl != null ? qrUrl : "/Users/suweiming/projects/wb/xcx-service/sservice-base/src/main/java/qrimg/qr.png";
            if (qrUrl != null) {
                bi3 = ImageIO.read(new URL(headurl));
            } else {
                bi3 = ImageIO.read(new File(headurl));
            }
            bi3 = ImageUtil.zoomInImage(bi3, 500);

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 调用mergeImage方法获得合并后的图像
        try {
            int h2 = bi2.getHeight();
            destImg = mergeImage(bi2, bi3, false, 0, h2);
            /**为图片添加描述*/
            destImg = drawTextInImg(
                    destImg,
                    new FontText(EmojiUtils.filterName(title),
                            3,
                            "#000000",
                            20,
                            "simsun"),
                    500, h2 + 50);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return destImg;
    }

    /**
     * @param title       标题
     * @param middlePanel 中间底图
     * @param slogan      宣传口号图
     * @param thumbnail   缩图
     * @param qrUrl       小程序码图
     * @return
     */
    public static BufferedImage myShreCard(String[] title, String middlePanel, String slogan, String thumbnail, String qrUrl) {
        // 读取待合并的文件
        BufferedImage bi1 = null;
        BufferedImage bi2 = null;
        BufferedImage bi3 = null;
        BufferedImage imgMiddlePanel = null;
        // 调用mergeImage方法获得合并后的图像
        BufferedImage destImg = null;
        try {
            // 团购缩略图
            bi1 = ImageUtil.zoomInImage(ImageIO.read(new URL(slogan)), 500);
            bi2 = ImageUtil.zoomInImage(ImageIO.read(new URL(thumbnail)), 400);
            imgMiddlePanel = ImageIO.read(new URL(middlePanel));
            bi3 = ImageUtil.zoomInImage(ImageIO.read(new URL(qrUrl)), 500);

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 调用mergeImage方法获得合并后的图像
        try {
            bi2 = merge2Image(imgMiddlePanel, bi2, 50, 50);
            destImg = mergeImage(bi1, bi2, false, 0, bi1.getHeight());
            destImg = mergeImage(destImg, bi3, false, 0, bi1.getHeight() + bi1.getHeight());
            if (title != null && title.length > 0) {
                for (int i = 0; i < title.length; i++) {
                    /**为图片添加描述*/
                    destImg = drawTextInImg(
                            destImg,
                            new FontText(EmojiUtils.filterName(title[i]),
                                    3,
                                    "#000000",
                                    20,
                                    "simsun"),
                            500, bi2.getHeight() + bi1.getHeight() + (i * 30));
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return destImg;
    }


    public static void main(String[] args) {
//        BufferedImage destImg = myQrCard(
//                "【只选对的】轻奢+潮牌外套5.5折",
//                "http://test1.ydlkeji.com/thumbnail/2018-10/1a5d7ba090154d3e909234f02ffa38b9_c.jpg",
//                null
//        );

        BufferedImage destImg2 = myShreCard(new String[]{"只选对的"},
                "http://123.57.39.2:8086/admin/imgs/xcx/img-panel.png",
                "http://123.57.39.2:8086/admin/imgs/xcx/logo-slogan.png",
                "http://test1.ydlkeji.com/thumbnail/2018-10/1a5d7ba090154d3e909234f02ffa38b9_c.jpg",
                "http://123.57.39.2:8086/admin/imgs/xcx/qr.png"
        );

        String baseurl = "/Users/suweiming/projects/wb/xcx-service/sservice-base/src/main/java/";
//        saveImage(destImg, baseurl, "qrimg/luguo.png", "png");
        saveImage(destImg2, baseurl, "qrimg/luguo.png", "png");


    }
}
